﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PIMS
{
    public class CountInfo
    {
        /// <summary>
        /// ItemInfo 类记录数组元素重复次数
        /// </summary>
        /// <param name="value">数组元素值</param>
        public CountInfo(string value)
        {
            Value = value;
            RepeatNum = 1;
        }
        /// <summary>
        /// 数组元素的值
        /// </summary>
        public string Value { get; set; }
        /// <summary>
        /// 数组元素重复的次数
        /// </summary>
        public int RepeatNum { get; set; } 
    }
    
    public class CountUtil
    {
        public static List<CountInfo> CountList(List<string> list)
        {
            List<CountInfo> info = new List<CountInfo>();

            // 集合 dic 用于存放统计结果
            Dictionary<string, CountInfo> dic = new Dictionary<string, CountInfo>();
            //开始统计每个元素重复次数
            foreach(string v in list)
            {
                if (dic.ContainsKey(v))
                {
                    // 数组元素再次，出现次数增加 1
                    dic[v].RepeatNum += 1;
                }
                else
                {
                    // 数组元素首次出现，向集合中添加一个新项
                    // 注意 ItemInfo类构造函数中，已经将重复
                    // 次数设置为 1
                    dic.Add(v, new CountInfo(v));
                }
            }
            foreach (CountInfo count in dic.Values)
            {
                info.Add(count);
            }
            List<CountInfo> sortInfo = info.OrderByDescending(o => o.RepeatNum).ToList();//降序排序
            return sortInfo;
        }
    }
}
